package com.yonyou.cyxdms.sysAuth.service.service.manage.employee;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoleilu.hutool.util.StrUtil;
import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DMSAuthException;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.bean.BeanMapperUtil;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.common.DateUtil;
import com.yonyou.cyx.function.utils.common.StringUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.StringUtil;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthCommonConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.controller.DbUnionCommonDto;
import com.yonyou.cyxdms.sysAuth.service.dto.CodeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.EmployeeUpdateDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.UserDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.role.RolePDto;
import com.yonyou.cyxdms.sysAuth.service.dto.user.EmployeeDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.userorgsource.UserorgSourceDTO;
import com.yonyou.cyxdms.sysAuth.service.entity.*;
import com.yonyou.cyxdms.sysAuth.service.entity.role.RolePO;
import com.yonyou.cyxdms.sysAuth.service.entity.userorgsource.UserorgSourcePO;
import com.yonyou.cyxdms.sysAuth.service.feign.BaseDataService;
import com.yonyou.cyxdms.sysAuth.service.feign.CustomerService;
import com.yonyou.cyxdms.sysAuth.service.feign.DataCenterService;
import com.yonyou.cyxdms.sysAuth.service.feign.IAuthProviderService;
import com.yonyou.cyxdms.sysAuth.service.feign.ImService;
import com.yonyou.cyxdms.sysAuth.service.feign.dto.BrokerInfoDTO;
import com.yonyou.cyxdms.sysAuth.service.feign.dto.UserInfoDTO;
import com.yonyou.cyxdms.sysAuth.service.mapper.*;
import com.yonyou.cyxdms.sysAuth.service.service.Login.UserLoginService;
import com.yonyou.cyxdms.sysAuth.service.service.Login.WechatScanLoginService;
import com.yonyou.cyxdms.sysAuth.service.service.jwt.JwtService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleCtrlService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleMenuActionService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleMenuRangeService;
import com.yonyou.cyxdms.sysAuth.service.service.role.RoleService;
import com.yonyou.cyxdms.sysAuth.service.service.userorgsource.UserorgSourceService;
import com.yonyou.cyxdms.sysAuth.service.utill.MD5Util;
import com.yonyou.cyxdms.sysAuth.service.vo.employee.*;
import com.yonyou.cyxdms.sysAuth.service.vo.org.OrgVO;
import com.yonyou.cyxdms.sysAuth.service.vo.weChat.SmsWxVo;
import com.yonyou.cyxdms.sysAuth.service.vo.weChat.WechatInfo;
import com.yonyou.cyxdms.sysmanage.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.EmployeeDictDto;
import com.yonyou.cyxdms.sysmanage.client.domains.dto.SmsPushDTO;
import com.yonyou.cyxdms.sysmanage.client.service.login.PushServices;
import com.yonyou.cyxdms.sysmanage.client.vo.employee.EmployeeOrgsVO;
import com.yonyou.cyxdms.sysmanage.client.vo.employee.EmployeeVO;
import io.swagger.annotations.Api;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 经销商员工信息
 *
 * @author renwd
 * @since 2019/7/9
 */

@Api(value = "经销商员工信息", tags = {"经销商员工信息"})
@Service
@Transactional(rollbackFor = Exception.class)
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, EmployeePO> implements EmployeeService {

    // 定义日志接口
    private static final Logger logger = LoggerFactory.getLogger(EmployeeServiceImpl.class);

    @Autowired
    private PermissionCtrlMapper permissionCtrlMapper;
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuActionMapper menuActionMapper;
    @Autowired
    private MenuRangeMapper menuRangeMapper;

    @Autowired
    private DealerInfoMapper dealerInfoMapper;
    @Autowired
    AscInfoMapper ascInfoMapper;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    ImService imService;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Value("${sms.templateId-2}")
    private String smsTemplateId2;

    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    PushServices pushService;

    @Autowired
    private UserOrgMapper userOrgMapper;

    @Autowired
    private OrgRoleMapper orgRoleMapper;


    @Autowired
    private PermissionMenuMapper permissionMenuMapper;

    @Autowired
    private PermissionMenuActionMapper permissionMenuActionMapper;

    @Autowired
    private PermissionMenuRangeMapper permissionMenuRangeMapper;

    @Autowired
    private IAuthProviderService authProviderService;
    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RoleCtrlService roleCtrlService;

    @Autowired
    private RoleMenuActionService roleMenuActionService;

    @Autowired
    private RoleMenuRangeService roleMenuRangeService;

    @Autowired
    private WechatScanLoginService wechatScanLoginService;

    @Autowired
    private UserorgSourceService userorgSourceService;

    @Autowired
    private JwtService jwtService;

    @Autowired
    private DataCenterService datacenterService;

    @Value("${pcwc.redirectUri2}")
    private String redirectUri;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {

        this.userMapper = userMapper;
    }

    @Autowired
    CustomerService customerService;

    /**
     * 查询所有的销售顾问
     *
     * @return
     * @throws ServiceBizException
     */
    @Override
    @Transactional(readOnly = true)
    public List<EmployeeVO> getEmployees(String queryCondition) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        logger.debug("loginInfo:{}", loginInfo);
        EmployeeDTO employeeDTO = new EmployeeDTO();
        employeeDTO.setAppId(loginInfo.getAppId());
        employeeDTO.setCompanyId(loginInfo.getCompanyId());
        employeeDTO.setEmployeeName(queryCondition);
        List<EmployeeVO> result = employeeMapper.getEmployees(employeeDTO);
        Collections.sort(result);
        return result;
    }

    @Override
    public EmployeeVO getemployeesbyemployeeno(String appId, String employeeno, String dealerCode) {
        EmployeeDTO employeeDTO = new EmployeeDTO();
        employeeDTO.setDealerCode(dealerCode);
        employeeDTO.setEmployeeNo(employeeno);
        employeeDTO.setAppId(appId);
        return employeeMapper.getEmployeesByEmployeeNO(employeeDTO);
    }

    /**
     * @description：获取销售顾问列表
     * @author ：quankk
     * @date ：Created in 2019/1/8 14:36
     * @modified By：
     */
    @Override
    public List<EmployeeVO> employeeByDealerCode(String appId, String dealerCode) {
        if (StringUtils.isNullOrEmpty(dealerCode)) {
            throw new ServiceBizException("经销商代码为空");
        }
        // 判断组织类型
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String orgId = null;
        Long orgType = loginInfoDto.getOrgType();
        logger.info("判断组织类型orgType:{}", orgType);
        if (!StringUtils.isNullOrEmpty(orgType)) {
            if (orgType == BaseDataDictConstants.ORG_TYPE_SECOND || orgType == BaseDataDictConstants.ORG_TYPE_BROKER) {
                logger.info("判断组织ID,orgId:{}", loginInfoDto.getOrgId());
                orgId = loginInfoDto.getOrgId().toString();
            }
        }
        return employeeMapper.employeeByDealerCode(appId, dealerCode, orgId);
    }

    /**
     * 模糊查询销售顾问编号
     *
     * @param dealerCode
     * @param employeeName
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.vo.EmployeeVO>
     * @author guorp
     * @since 2019/1/22
     */
    @Override
    public List<EmployeeVO> getEmployeeNoByLikeEmployeeName(String appId, String dealerCode, String employeeName) {
        return employeeMapper.getEmployeeNoByLikeEmployeeName(appId, dealerCode, employeeName);
    }

    /**
     * 根据角色查询销售顾问
     *
     * @param roleType
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.vo.EmployeeVO>
     * @author renwd
     * @since 2019/3/21
     */
    @Override
    public List<EmployeeVO> getEmployeesByPosition(Integer roleType) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return employeeMapper.getEmployeesByPosition(roleType, BaseDataDictConstants.IS_ON_JOB,
                loginInfo.getOwnerCode());
    }

    @Override
    public IPage<EmployeeUsersVO> searchUserEmployees(Page page, Map<String, Object> queryCondition) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryCondition.put("appId", loginInfoDto.getAppId());
        queryCondition.put("companyId", loginInfoDto.getCompanyId());
        logger.debug("queryCondition:{}", queryCondition);
        List<EmployeeUsersVO> voList = employeeMapper.searchUserEmployees(page, queryCondition);
        page.setRecords(voList);
        return page;
    }

    @Autowired
    private BaseDataService baseDataService;

    @Autowired
    private EmployeeRoleMapper employeeRoleMapper;

    /**
     * 销售顾问下拉数据
     *
     * @return java.util.List<com.yonyou.cyxdms.sysAuth.service.vo.employee.ConsultantVO>
     * @author renwd
     * @since 2019/7/9
     */
    @Transactional(readOnly = true)
    @Override
    public List<ConsultantVO> qryPowerSalesConsultant() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return employeeMapper.qryPowerSalesConsultant(ManageDictCodeConstants.EMPLOYEE_ISJOB,
                loginInfoDto.getOwnerCode(), ManageDictCodeConstants.SALES_CONSULTANT, loginInfoDto.getAppId());
    }

    /**
     * 电销顾问下拉数据
     *
     * @return java.util.List<com.yonyou.cyxdms.sysAuth.service.vo.employee.ConsultantVO>
     * @author renwd
     * @since 2019/7/9
     */
    @Transactional(readOnly = true)
    @Override
    public List<ConsultantVO> qryTelemarkConsultant() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return employeeMapper.qryPowerSalesConsultant(ManageDictCodeConstants.EMPLOYEE_ISJOB,
                loginInfoDto.getOwnerCode(), ManageDictCodeConstants.SALES_TELECONSULTANT, loginInfoDto.getAppId());
    }

    /**
     * 员工信息下拉框调用的方法
     *
     * @param queryParam
     * @return java.util.List<com.yonyou.cyxdms.sysAuth.service.vo.employee.EmployeeSelectVO>
     * @author renwd
     * @since 2019/7/9
     */
    @Transactional(readOnly = true)
    @Override
    public List<EmployeeSelectVO> selectEmployees(Map<String, Object> queryParam) {
        logger.debug("selectEmployees：{}", queryParam);
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        queryParam.put("isOnJob", ManageDictCodeConstants.EMPLOYEE_ISJOB);
        queryParam.put("dealerCode", loginInfoDto.getOwnerCode());
        queryParam.put("appId", loginInfoDto.getAppId());
        return employeeMapper.selectEmployees(queryParam);
    }

    /**
     * 根据dealer_code查询销售顾问
     *
     * @param dealerCode
     * @return java.util.List<com.yonyou.cyxdms.sysAuth.service.vo.employee.ConsultantVO>
     * @author renwd
     * @since 2019/7/9
     */
    @Transactional(readOnly = true)
    @Override
    public List<ConsultantVO> qryPowerDealerSalesConsultant(String dealerCode) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return employeeMapper.qryPowerSalesConsultant(ManageDictCodeConstants.EMPLOYEE_ISJOB, dealerCode,
                ManageDictCodeConstants.SALES_CONSULTANT, loginInfoDto.getAppId());
    }

    @Override
    public IPage<EmployeeSearchVO> search(Page<EmployeeSearchVO> page, Map<String, String> param) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        param.put("superAdmin", loginInfoDto.getOwnerCode() + "_ADMIN");
        param.put("companyId", loginInfoDto.getCompanyId().toString());
        param.put("appId", loginInfoDto.getAppId());
        if (!StringUtils.isNullOrEmpty(param.get("typeUser"))) {
            param.remove("typeUser");
            param.put("typeUser", String.valueOf(ManageDictCodeConstants.DATA_SOURCES_BY_GROUP));
        }
        List<EmployeeSearchVO> result = employeeMapper.search(page, param);
        if (page.getCurrent() > page.getPages()) {
            Page<EmployeeSearchVO> page2 = new Page(1, page.getSize());
            List<EmployeeSearchVO> result2 = employeeMapper.search2(page, param);
            page2.setRecords(result2);
            return page2;
        }
        page.setRecords(result);
        return page;
    }

    /**
     * @author ：李贺
     * @date ：2019/7/10 17:04 @description：
     */
    @Override
    public List<CodeDTO> findTcCodeByType(Long id) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("type", id);
        queryParam.put("appId", loginInfoDto.getAppId());
        List<CodeDTO> result = baseDataService.queryTcCodeByType(queryParam).getData();
        return result;
    }

    /**
     * @author ：quankk
     * @date ：2019/7/10 17:26 @description：
     */
    @Override
    public EmployeeVO findByEmployeeId(Long id) {
        EmployeeVO employeepo = employeeMapper.findById(id);
        return employeepo;
    }

    /**
     * @author ：quankk
     * @date ：2019/7/10 18:08 @description：
     */
    @Override
    public void updateEmpById(Long id, EmployeeUpdateDTO empDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        EmployeePO employeepo = employeeMapper.selectById(id);
        Integer empId = employeepo.getEmpId().intValue();
        EmpPo emp = empMapper.selectById(empId);
        LambdaQueryWrapper<EmpPo> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(EmpPo::getMobilePhone, empDto.getPhone())
                .eq(EmpPo::getIsOnjob, ManageDictCodeConstants.EMPLOYEE_ISJOB).ne(EmpPo::getEmpId, empId);

        List<EmpPo> listEmpPo = empMapper.selectList(queryWrapper);
        boolean mobileIsTrue;
        if (CommonUtils.isNullOrEmpty(listEmpPo)) {
            mobileIsTrue = true;
        } else {
            mobileIsTrue = false;
        }

        LambdaQueryWrapper<EmpPo> certificatedQueryWrapper = new QueryWrapper().lambda();
        certificatedQueryWrapper.eq(EmpPo::getCertificateId, empDto.getCertificateId()).ne(EmpPo::getEmpId, empId);
        List<EmpPo> certificatedListEmpPo = empMapper.selectList(certificatedQueryWrapper);
        boolean certificatedIdIsTrue;
        if (CommonUtils.isNullOrEmpty(certificatedListEmpPo)) {
            certificatedIdIsTrue = true;
        } else {
            certificatedIdIsTrue = false;
        }
        if (certificatedIdIsTrue == false) {
            throw new ServiceBizException("该身份证号已经存在");
        }
        if (mobileIsTrue) {
            // 保存员工信息
            setEmp(empDto, emp);
            empMapper.updateById(emp);

            setEmployee(employeepo, empDto, empId, loginInfoDto);
            employeeMapper.updateById(employeepo);

            // 删除之前保存的员工全部角色信息
//            List<String> roles = empDto.getEmployeeRoles();
//            LambdaQueryWrapper<EmployeeRolePO> employeeRolePOLambdaQueryWrapper = new QueryWrapper().lambda();
//            employeeRolePOLambdaQueryWrapper.eq(EmployeeRolePO::getEmployeeId, id);
//            employeeRoleMapper.delete(employeeRolePOLambdaQueryWrapper);
//            EmployeeRolePO erPo;
//            // 保存修改之后的员工角色信息
//            if (roles.size() > 0) {
//                for (int i = 0; i < roles.size(); i++) {
//                    erPo = new EmployeeRolePO();
//                    erPo.setEmployeeId(id.intValue());
//                    erPo.setRole(Integer.valueOf(roles.get(i)));
//                    employeeRoleMapper.insert(erPo);
//                }
//            }

            try {
                LambdaQueryWrapper<UserPO> lambdaQueryWrapper = new QueryWrapper().lambda();
                lambdaQueryWrapper.eq(UserPO::getEmpId, empId).eq(UserPO::getAppId, employeepo.getAppId());
                UserPO userpo = userMapper.selectOne(lambdaQueryWrapper);
                LambdaQueryWrapper<EmpPo> lambdaQueryWrapper1 = new QueryWrapper().lambda();
                lambdaQueryWrapper1.eq(EmpPo::getEmpId, empId).eq(EmpPo::getAppId, employeepo.getAppId());
                EmpPo empPo = empMapper.selectOne(lambdaQueryWrapper1);

                UserInfoDTO userInfoDTO = new UserInfoDTO();
                userInfoDTO.setUserId(Long.parseLong(String.valueOf(userpo.getUserId())));
                userInfoDTO.setAppId(userpo.getAppId());
                userInfoDTO.setUserToken(userpo.getUserId().toString());
                userInfoDTO.setUserName(empPo.getEmployeeName());
                userInfoDTO.setIsStop(0);
                // userInfoDTO.setDealerCode(employeePO.getOwnerCode());
                // userInfoDTO.setPhone(employeePO.getMobile());
                userInfoDTO.setUserCode(userpo.getUserCode());
                userInfoDTO.setEmployeeNo(employeepo.getEmployeeNo());
                // fixme 把用户信息同步到im
                imService.saveOrUpdate(userInfoDTO);
                logger.debug("人员信息同步到IM完成");

                BrokerInfoDTO brokerInfoDTO = new BrokerInfoDTO();
                brokerInfoDTO.setAppId(userpo.getAppId());
                brokerInfoDTO.setUserToken(userpo.getUserId().toString());
                brokerInfoDTO.setUid(Long.parseLong(String.valueOf(userpo.getUserId())));
                brokerInfoDTO.setDmsId(userpo.getUserId().toString());
                brokerInfoDTO.setName(empPo.getEmployeeName());
                // fixme todo 这里设置职位
                brokerInfoDTO.setType(1);
                // brokerInfoDTO.setEmail(employeePO.geteMail());
                // brokerInfoDTO.setMobile(employeePO.getMobile());
                // brokerInfoDTO.setGender(Integer.valueOf(Gender.Male.getCode()).equals(employeePO.getGender())
                // ? 1 : Integer.valueOf(Gender.Female.getCode()).equals(employeePO.getGender())
                // ? 2 : 0);
                brokerInfoDTO.setIsDeleted(0);
                // brokerInfoDTO.setDealerCode(employeePO.getOwnerCode());
                // brokerInfoDTO.setPhone(employeePO.getPhone());
                brokerInfoDTO.setUserCode(employeepo.getEmployeeNo());
                // 设置日期尝试
                brokerInfoDTO.setWorkTime(LocalDateTime.now());
                brokerInfoDTO.setFoundDate(LocalDateTime.now());
                logger.debug("人员信息同步到broker完成");
            } catch (Exception e) {
                logger.error("同步用户数据异常：", e);
            }

//            员工信息(DMS->PUSH->车间) DMS-PUSH 修改
//            pushservice.sendEmployee(employee.getLongId(), PushCommonPubConstants.OPERATE_UP);
        } else {
            throw new ServiceBizException("该手机号已存在");
        }
    }

    private void setEmployee(EmployeePO employeepo, EmployeeUpdateDTO empDto, Integer empId,
                             LoginInfoDto loginInfoDto) {
        employeepo.setOrgId((long) empDto.getOrgId());
        employeepo.setPositionCode(empDto.getPositionCode());
        employeepo.setIsMajor(ManageDictCodeConstants.STATUS_IS_YES);
        employeepo.setEmpId(empId.longValue());
        employeepo.setCompanyId(loginInfoDto.getCompanyId());
        // employeePO.setOwnerCode(orgMapper.getOwerCodebyOrgId(loginInfoDto.getOrgId()));
        employeepo.setTechnicianGrade(
                !StringUtils.isNullOrEmpty(empDto.getTechnicianGrade()) ? empDto.getTechnicianGrade() : null);
    }

    private void setEmp(EmployeeUpdateDTO empDto, EmpPo emp) {
        emp.setEmployeeName(empDto.getEmployeeName());
        emp.setGender(Math.toIntExact(!StringUtils.isNullOrEmpty(empDto.getGender()) ? empDto.getGender()
                : ManageDictCodeConstants.GENDER_NOT_DEFINE));
        emp.setCertificateId(empDto.getCertificateId());
        emp.setMobilePhone(empDto.getPhone());
        emp.seteMail(empDto.geteMail());
        if (empDto.getBirthday() != null) {
            emp.setBirthday(DateUtil.parseDefaultDateTime(empDto.getBirthday()));
        } else {
            emp.setBirthday(new Date());
        }
        emp.setAddress(empDto.getAddress());
        emp.setZipCode(empDto.getZipCode());
        emp.setIsOnjob(empDto.getIsOnjob().intValue());
        emp.setDataSources(ManageDictCodeConstants.DATA_SOURCES_BY_OWNER);
        if (empDto.getIsOnjob() == ManageDictCodeConstants.EMPLOYEE_ISJOB) {
            emp.setUserStatus(ManageDictCodeConstants.STATUS_QY);
        } else {
            emp.setUserStatus(ManageDictCodeConstants.STATUS_JY);
        }

        if (empDto.getFoundDate() != null) {
            emp.setFoundDate(DateUtil.parseDefaultDateTime(empDto.getFoundDate()));
        } else {
            emp.setFoundDate(new Date());
        }

        // 如果在职状态为“离职”并且离职日期为空，则默认离职时间为当前时间
        if ((ManageDictCodeConstants.EMPLOYEE_NOJOB + "").equals(empDto.getIsOnjob() + "")
                && empDto.getDimissionDate() == null) {
            emp.setDimissionDate(new Date());
        } else {
            emp.setDimissionDate(empDto.getDimissionDate());
        }
    }

    /**
     * @author ：maxingjian
     * @date ：2019/7/12 @description：
     */
    @Override
    public void lock(Long id) {
        EmployeePO employeepo = employeeMapper.selectById(id);
        LambdaQueryWrapper<UserPO> poLambdaQueryWrapper = new QueryWrapper().lambda();
        poLambdaQueryWrapper.eq(UserPO::getEmpId, employeepo.getEmpId()).eq(UserPO::getAppId, employeepo.getAppId());
        UserPO userPo = userMapper.selectOne(poLambdaQueryWrapper);
        userPo.setLockFlag(ManageDictCodeConstants.STATUS_IS_YES);
        userPo.setFailureNum(0);
        userMapper.updateById(userPo);
    }

    @Override
    @Transactional
    public PositionVO addRoles(AddRolePO addrolepo) {
        logger.info("保存用户角色开始");
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Integer dataType = ManageDictCodeConstants.DATA_TYPE_BY_OWNER;
        String appId = loginInfoDto.getAppId();

        List<Long> roleIds = addrolepo.getRoleId();

        Long userOrgId = addrolepo.getUserOrgId();

        logger.info("保存用户角色中");
        if (roleIds.size() == 0) {
            throw new ServiceBizException("请选择角色");
        }

        for (Long newRoleId : roleIds) {

            // 插入orgRole
            OrgRolePO orgrolepo = new OrgRolePO();
            orgrolepo.setUserOrgId(userOrgId);
            orgrolepo.setRoleId(newRoleId);
            orgrolepo.setIsDeleted(0);
            orgRoleMapper.insert(orgrolepo);
        }
        Long createdBy = loginInfoDto.getUserId();
        // 插入角色模板的菜单按钮
        permissionMenuMapper.insertUserMenu(roleIds, userOrgId, createdBy, appId);
        // 插入其他
        permissionMenuMapper.insertOtherMenu(userOrgId, loginInfoDto.getAppId(), createdBy, dataType.longValue());
        // 删除
        permissionCtrlMapper.deletePermissionCtrlByUserOrgId(userOrgId);
        permissionCtrlMapper.addUserPermissionCtrl(userOrgId, roleIds, createdBy.intValue(), appId);
        // 菜单按钮和菜单权限
        permissionMenuRangeMapper.insertRangeByOthers(roleIds, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE,
                userOrgId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, loginInfoDto.getUserId().toString());
        permissionMenuActionMapper.insertActionByOthers(roleIds, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE,
                userOrgId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, loginInfoDto.getUserId().toString());

        return employeeMapper.findUserOrgPosition(userOrgId);
    }

    /**
     * @author ：maxingjian
     * @date ：2019/7/12 @description：
     */
    @Override
    public void removeLock(Long id) {
        EmployeePO employeepo = employeeMapper.selectById(id);
        LambdaQueryWrapper<UserPO> lambdaQueryWrapper = new QueryWrapper().lambda();
        lambdaQueryWrapper.eq(UserPO::getEmpId, employeepo.getEmpId()).eq(UserPO::getAppId, employeepo.getAppId());
        UserPO userPo = userMapper.selectOne(lambdaQueryWrapper);
        userPo.setLockFlag(ManageDictCodeConstants.STATUS_IS_NOT);
        userPo.setFailureNum(0);
        userMapper.updateById(userPo);
    }

    @Override
    public List<Map<String, Object>> findEmployeeRoleById(Long id) {
        List<Map<String, Object>> employeeRoleById = employeeMapper.findEmployeeRoleById(id);
        return employeeRoleById;
    }

    /**
     * @author ：quankk
     * @date ：2019/7/19 11:03
     * @description：新增员工信息
     */
    @Override
    public Long addEmployee(EmployeeUpdateDTO empDto) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        EmpPo emp = new EmpPo();
//        EmployeeRolePO erPo;
        // 员工编号
        String employeeNo = loginInfoDto.getOwnerCode() + empDto.getEmployeeNo();
        LambdaQueryWrapper<EmployeePO> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(EmployeePO::getEmployeeNo, employeeNo).eq(EmployeePO::getAppId, loginInfoDto.getAppId());
        List<EmployeePO> empPoList = employeeMapper.selectList(queryWrapper);
        LambdaQueryWrapper<EmpPo> phoneQueryWrapper = new QueryWrapper().lambda();
        phoneQueryWrapper.eq(EmpPo::getMobilePhone, empDto.getPhone()).eq(EmpPo::getAppId, loginInfoDto.getAppId());
        List<EmpPo> phoneEmpPoList = empMapper.selectList(phoneQueryWrapper);
        LambdaQueryWrapper<EmpPo> certificateIdQueryWrapper = new QueryWrapper().lambda();
        certificateIdQueryWrapper.eq(EmpPo::getCertificateId, empDto.getCertificateId())
                .eq(EmpPo::getEmpId, loginInfoDto.getOwnerCode()).eq(EmpPo::getAppId, loginInfoDto.getAppId());
        List<EmpPo> certificateEmpPoList = empMapper.selectList(certificateIdQueryWrapper);
        if (!CommonUtils.isNullOrEmpty(certificateEmpPoList)) {
            throw new ServiceBizException("该身份证号已经存在");
        }
        if (CommonUtils.isNullOrEmpty(empPoList)) {
            if (CommonUtils.isNullOrEmpty(phoneEmpPoList)) {
                // emp.setEmployeeNo(employeeNo);
                empDto.setFoundDate(DateUtil.parseDefaultDateTime(new Date()));
                setEmp(empDto, emp);
                // emp.setUserCode(empDto.getEmployeeNo());
                emp.setDataSources(ManageDictCodeConstants.DATA_SOURCES_BY_OWNER);
                if (empDto.getIsOnjob() == ManageDictCodeConstants.EMPLOYEE_ISJOB) {
                    emp.setUserStatus(ManageDictCodeConstants.STATUS_QY);
                } else {
                    emp.setUserStatus(ManageDictCodeConstants.STATUS_JY);
                }
                // 建档时间 ，如果不填 系统默认为当前时间
                if (empDto.getFoundDate() != null) {
                    emp.setFoundDate(DateUtil.parseDefaultDateTime(empDto.getFoundDate()));
                } else {
                    emp.setFoundDate(new Date());
                }
                // 如果在职状态为“离职”并且离职日期为空，则默认离职时间为当前时间
                if ((ManageDictCodeConstants.EMPLOYEE_NOJOB + "").equals(empDto.getIsOnjob() + "")
                        && empDto.getDimissionDate() == null) {
                    emp.setDimissionDate(new Date());
                } else {
                    emp.setDimissionDate(empDto.getDimissionDate());
                }
                emp.setCompanyId(loginInfoDto.getCompanyId().intValue());
                empMapper.insert(emp);
                Long empid = emp.getEmpId();
                // 保存数据到TM_EMPLOYEE表
                EmployeePO employee = new EmployeePO();
                employee.setEmployeeNo(employeeNo);
                setEmployee(employee, empDto, empid.intValue(), loginInfoDto);
                employeeMapper.insert(employee);

//                // 保存用户角色
//                List<String> list = empDto.getEmployeeRoles();
//                for (int i = 0; i < list.size(); i++) {
//                    erPo = new EmployeeRolePO();
//                    erPo.setEmployeeId(employee.getEmployeeId());
//                    erPo.setRole(Integer.valueOf(list.get(i)));
//                    erPo.setDealerCode(loginInfoDto.getOwnerCode());
//                    erPo.setOrganizationId(empDto.getOrganizationId());
//                    employeeRoleMapper.insert(erPo);
//                }
                return emp.getEmpId();
            } else {
                throw new ServiceBizException("该手机号已存在");
            }
        } else {
            throw new ServiceBizException("该员工编号已经存在");
        }
    }

    /**
     * @return
     * @author :maxingjian
     * @date :2019/12/19 14:10
     */
    @Override
    public String findAuthorization(Long menuId, String alias, String salesColumn, String orgColumn,
                                    boolean isDealer, boolean needSaleCode, boolean needServiceCode) {
        StringBuffer str = new StringBuffer();
        String strSqlResult = null;
        try {
            LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
            logger.debug("loginInfoDto:{}", loginInfoDto);
            String appId = loginInfoDto.getAppId();
            String userId = loginInfoDto.getUserId().toString();
            strSqlResult = employeeMapper.findAuthorization(menuId, loginInfoDto.getUserOrgId().toString(), appId);
            if (StringUtils.isNullOrEmpty(strSqlResult)) {
                strSqlResult = ManageDictCodeConstants.ORG_ALL + "";
            }
            boolean isOrgColumnNotBlank = StrUtil.isNotBlank(orgColumn);
            Integer rangeCode = Integer.valueOf(strSqlResult);
            if (StringUtils.isNullOrEmpty(alias)) { // alias为null
                if (rangeCode == ManageDictCodeConstants.IAM) { // 本人
                    str.append(" and " + salesColumn).append(" = '" + loginInfoDto.getUserId() + "'");
                    if (isOrgColumnNotBlank) {
                        str.append(" and " + orgColumn).append(" = '" + loginInfoDto.getOrgId() + "'");
                    }
                    str.append(" and APP_ID ").append(" = '" + appId + "'");
                } else if (rangeCode == ManageDictCodeConstants.IAM_ORGANIZATION) { // 本组织
                    if (isOrgColumnNotBlank) {
                        str.append(" and " + orgColumn).append(" = '" + loginInfoDto.getOrgId() + "'");
                    }
                    str.append(" and APP_ID ").append(" = '" + appId + "'");
                } else if (rangeCode == ManageDictCodeConstants.IAM_ORGANIZATION_SUB) { // 本组织及下属
                    if (isOrgColumnNotBlank) {
                        String str1 = loginInfoDto.getOrgIds();
                        String[] strs = str1.split(",");
                        str.append(" and " + orgColumn).append(" in ( ");
                        if (str1.length() > 0) {
                            for (int i = 0, len = strs.length; i < len; i++) {
                                str.append("'").append(strs[i]).append("'");
                                if (i < strs.length - 1) {
                                    str.append(",");
                                }
                            }
                            str.append(" ) ");
                        }
                    }
                    str.append(" and APP_ID =").append("'" + appId + "'");
                    logger.debug("本组织及下属{}:" + str.toString());
                } else if (rangeCode == ManageDictCodeConstants.ORG_ALL) { // 所有
                    String ownerCode = loginInfoDto.getOwnerCode();
                    if (loginInfoDto.getDataType().toString()
                            .equals(String.valueOf(SysAuthDictCodeConstants.DATA_TYPE_BY_OWNER))) {
                        if (isDealer) {
                            Integer orgType = getOwnerOrgType(loginInfoDto.getUserOrgId());
                            if (!StringUtils.isNullOrEmpty(orgType) && orgType.toString()
                                    .equals(String.valueOf(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY))) {
                                str.append(" and OWNER_CODE ").append(" in ('").append(loginInfoDto.getOwnerCode());
                                str.append(getAllCode(loginInfoDto.getCompanyId(), needSaleCode, needServiceCode));
                                str.append("') and APP_ID =").append("'" + appId + "'");
                            } else {
                                str.append(" and OWNER_CODE").append(" ='" + ownerCode + "' and APP_ID =")
                                        .append("'" + appId + "'");
                            }
                        } else {
                            str.append(" and OWNER_CODE").append(
                                    " in ('" + ownerCode + "','-1','" + loginInfoDto.getGroupCode() + "') and APP_ID =")
                                    .append("'" + appId + "'");
                        }
                    } else {
                        str.append(" and APP_ID =").append("'" + appId + "'");
                    }
                } else {
                    throw new ServiceBizException("用户id为空或不存在");
                }
                return str.toString();
            }
            if (menuId == null) {
                // str.append(" and APP_ID").append(" = '" + appId + "'");
            } else {
                if (rangeCode == ManageDictCodeConstants.IAM) { // 本人
                    str.append(" and " + alias + "." + salesColumn).append(" = '" + loginInfoDto.getUserId() + "'");
                    if (isOrgColumnNotBlank) {
                        str.append(" and " + alias + "." + orgColumn).append(" = '" + loginInfoDto.getOrgId() + "'");
                    }
                    str.append(" and " + alias + ".APP_ID ").append(" = '" + appId + "'");
                } else if (rangeCode == ManageDictCodeConstants.IAM_ORGANIZATION) { // 本组织
                    if (isOrgColumnNotBlank) {
                        str.append(" and " + alias + "." + orgColumn).append(" = '" + loginInfoDto.getOrgId() + "'");
                    }
                    str.append(" and " + alias + ".APP_ID ").append(" = '" + appId + "'");
                } else if (rangeCode == ManageDictCodeConstants.IAM_ORGANIZATION_SUB) { // 本组织及下属
                    if (isOrgColumnNotBlank) {
                        String str1 = loginInfoDto.getOrgIds();
                        String[] strs = str1.split(",");
                        str.append(" and " + alias).append("." + orgColumn).append(" in ( ");
                        if (str1.length() > 0) {
                            for (int i = 0, len = strs.length; i < len; i++) {
                                str.append("'").append(strs[i]).append("'");
                                if (i < strs.length - 1) {
                                    str.append(",");
                                }
                            }
                            str.append(" )");
                        }
                    }
                    str.append(" and " + alias + ".APP_ID =").append("'" + appId + "'");
                    logger.debug("本组织及下属{}:" + str.toString());
                } else if (rangeCode == ManageDictCodeConstants.ORG_ALL) { // 所有
                    String ownerCode = loginInfoDto.getOwnerCode();
                    if (loginInfoDto.getDataType().toString()
                            .equals(String.valueOf(SysAuthDictCodeConstants.DATA_TYPE_BY_OWNER))) {
                        if (isDealer) {
                            Integer orgType = getOwnerOrgType(loginInfoDto.getUserOrgId());
                            if (!StringUtils.isNullOrEmpty(orgType) && orgType.toString()
                                    .equals(String.valueOf(ManageDictCodeConstants.ORG_TYPE_DEALER_COMPANY))) {
                                str.append(" and " + alias).append(".OWNER_CODE").append(" in ('")
                                        .append(loginInfoDto.getOwnerCode());
                                str.append(getAllCode(loginInfoDto.getCompanyId(), needSaleCode, needServiceCode));
                                str.append("') and " + alias + ".APP_ID =").append("'" + appId + "'");
                            } else {
                                str.append(" and " + alias).append(".OWNER_CODE")
                                        .append(" ='" + ownerCode + "' and " + alias + ".APP_ID =")
                                        .append("'" + appId + "'");
                            }
                        } else {
                            str.append(" and " + alias).append(".OWNER_CODE").append(" in ('" + ownerCode + "','-1','"
                                    + loginInfoDto.getGroupCode() + "') and " + alias + ".APP_ID =")
                                    .append("'" + appId + "'");
                        }
                    } else {
                        str.append(" and " + alias + ".APP_ID =").append("'" + appId + "'");
                    }
                } else {
                    throw new ServiceBizException("用户id为空或不存在");
                }
            }
        } catch (Exception e) {
            logger.debug("失败", e);
        }
        return str.toString();
    }

    private Integer getOwnerOrgType(Long userOrgId) {
        Integer type = null;
        UserOrgPO po = userOrgMapper.selectById(userOrgId);
        if (po != null) {
            type = po.getOwnerOrgType();
        }
        return type;
    }

    private String getAllCode(Long companyId, boolean needSaleCode, boolean needServiceCode) {
        StringBuilder str = new StringBuilder();
        if (needSaleCode) {
            LambdaQueryWrapper<DealerInfoPO> queryDealerWrapper = new QueryWrapper<DealerInfoPO>().lambda();
            queryDealerWrapper.eq(DealerInfoPO::getCompanyId, companyId);
            List<DealerInfoPO> listDealer = dealerInfoMapper.selectList(queryDealerWrapper);
            if (listDealer.size() > 0) {
                for (DealerInfoPO dealerInfoPo : listDealer) {
                    str.append("','").append(dealerInfoPo.getDealerCode());
                }
            }
        }
        if (needServiceCode) {
            LambdaQueryWrapper<AscInfoPO> queryAscWrapper = new QueryWrapper<AscInfoPO>().lambda();
            queryAscWrapper.eq(AscInfoPO::getCompanyId, companyId);
            List<AscInfoPO> listAsc = ascInfoMapper.selectList(queryAscWrapper);
            if (listAsc.size() > 0) {
                for (AscInfoPO ascInfoPo : listAsc) {
                    str.append("','").append(ascInfoPo.getAscCode());
                }
            }
        }
        return str.toString();
    }

    /**
     * @return
     * @author :duxg
     * @date :2019/7/29 14:10
     */
    @Override
    public String findAuthorization(Long menuId, String alias, String salesColumn, String orgColumn) {
        return findAuthorization(menuId, alias, salesColumn, orgColumn, false);
    }

    /**
     * @return
     * @author :maxingjian
     * @date :2019/12/25
     */
    @Override
    public String findAuthorization(Long menuId, String alias, String salesColumn, String orgColumn,
                                    boolean isDealer) {
        return findAuthorization(menuId, alias, salesColumn, orgColumn, isDealer, false, false);
    }

    @Override
    public String findPermissionRange(Long menuId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appId = loginInfoDto.getAppId();
        return employeeMapper.findAuthorization(menuId, loginInfoDto.getUserOrgId().toString(), appId);

    }

    @Override
    public EmployeeDTO loginByNameOrPhone(String vUser, String vPwd, String isInit) {
        return employeeMapper.loginByNameOrPhone(vUser, vPwd, isInit);
    }

    @Override
    public UserDTO getUserInfo(String id) {
        return employeeMapper.getUserInfo(id);
    }

    @Override
    public int resetPwdByPhone(String vPwd, String vMobile, String vPwdOld, String flag) {
        return employeeMapper.resetPwdByPhone(vPwd, vMobile, vPwdOld, flag);
    }

    @Override
    public int resetPwdByPno(String name, String pwd, String newPassword) {
        return employeeMapper.resetPwdByPno(name, pwd, newPassword);
    }

    @Override
    public EmployeeDTO getEmpInfoByOpenId(String openId) {
        return employeeMapper.getEmpInfoByOpenId(openId);
    }

    @Override
    public EmployeeDTO getEmpInfoByAppId(String openId) {
        return employeeMapper.getEmpInfoByAppId(openId);
    }

    @Override
    public int updatewxopenid(String vMobile, String openId) {
        return employeeMapper.updateWXOpenId(vMobile, openId);
    }

    @Override
    public int updateAppOpenId(String vMobile, String openId, String vwxnickname) {
        return employeeMapper.updateAppOpenId(vMobile, openId, vwxnickname);
    }

    @Override
    public int updateInitPwd(String vMobile, String vinitpwd) {
        return employeeMapper.updateInitPwd(vMobile, vinitpwd);
    }

    @Override
    public EmployeeDTO findEmpInfo(String vUser) {
        return employeeMapper.findEmpInfo(vUser);
    }

    @Override
    public EmployeeDTO findEmpBind(String vMobile) {
        return employeeMapper.findEmpBind(vMobile);
    }

    @Override
    public int updateLoginFailNum(String vUser, int vState, int nLoginFailNum) {
        return employeeMapper.updateLoginFailNum(vUser, vState, nLoginFailNum);
    }

    @Override
    public List<UserDTO> checkUser(String nemployeeid) {
        DbUnionCommonDto searchEntity = new DbUnionCommonDto();
        searchEntity.setQueryConditions("a.nEmployeeID", 0, nemployeeid);
        return userMapper.getUserInformation(searchEntity);
    }

    @Override
    public void updatereg(String userid, String reg) {
//        UserPO po = new UserPO();
//        UserPO po2 = new UserPO();
//        po = po.selectById(userid);
//        BeanUtils.copyProperties(po, po2);
//        //  po2.setrEG_ID(reg);
//
//        po2.updateById();
    }

    @Override
    public EmployeeDictDto getEmployeeById(Long employeeId) {
        String messageFormat = BaseDataCommonConstants.EMPLOYEE_CACHE_EMPLOYEEID;
        Object employeeDictDto = redisClient.hget(messageFormat, employeeId.toString());
        if (null == employeeDictDto) {
            // 查询所有数据
            employeeDictDto = employeeMapper.getEmployeeById(employeeId);
            logger.info("查询用户Dto:{}", employeeDictDto);
            if (null == employeeDictDto) {
                return null;
            }
            redisClient.hsetExpire(messageFormat, employeeId.toString(), JSONUtil.objectToJson(employeeDictDto),
                    SysAuthCommonConstants.EXPIRE_TIME_ONE_DAY);
        }
        return JSONUtil.jsonToObj(JSONUtil.objectToJson(employeeDictDto), EmployeeDictDto.class);
    }

    @Override
    public List<EmployeeOrgsVO> getSalesmans() {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Integer employeeId = loginInfo.getEmployeeId().intValue();

        Integer appRole = loginInfo.getAppRole().intValue();

        List<EmployeeOrgsVO> employeeorgsvos = new ArrayList<>();
        // 判断当前登录是否为展厅经理
        if (appRole.equals(BaseDataDictConstants.SALES_AUDIT)) {

            String orgIds = loginInfo.getOrgIds();
            employeeorgsvos = employeeMapper.selectEmployeesByOrgIds(orgIds, BaseDataDictConstants.HALL_CONSULTANT);
            return employeeorgsvos;
        }
        EmployeeOrgsVO employeeOrgsVO = new EmployeeOrgsVO();
        employeeOrgsVO.setUserId(loginInfo.getUserId().intValue());
        employeeOrgsVO.setEmpId(loginInfo.getEmpId().intValue());
        employeeOrgsVO.setEmployeeId(employeeId);
        employeeOrgsVO.setEmployeeName(loginInfo.getUserName());
        employeeOrgsVO.setUserCode(loginInfo.getUserCode());
        employeeorgsvos.add(employeeOrgsVO);
        return employeeorgsvos;
    }

    @Override
    public List<EmployeeOrgsVO> getDirSalesName(Long menuId, String positionCode) {
        List<EmployeeOrgsVO> employeeorgsvos = new ArrayList<>();
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String str;
        str = employeeMapper.findAuthorization(menuId, loginInfo.getUserOrgId().toString(),
                loginInfo.getAppId());
        Map<String, Object> params = new HashMap<>();
        List<String> list = new ArrayList<>();
        String[] strs = positionCode.split(",");
        if (strs.length > 0) {
            for (int i = 0; i < strs.length; i++) {
                list.add(strs[i]);
            }
        }
        params.put("positionCode", list);
        if (StringUtils.isNullOrEmpty(str)) {
            params.put("companyId", loginInfo.getCompanyId());
            employeeorgsvos = employeeMapper.selectEmployeesByParams(params);
            return employeeorgsvos;
        }
        if (str.equals(String.valueOf(ManageDictCodeConstants.IAM))) {
            params.put("userId", loginInfo.getUserId());
            employeeorgsvos = employeeMapper.selectEmployeesByParams(params);

        } else if (str.equals(String.valueOf(ManageDictCodeConstants.IAM_ORGANIZATION))) {
            params.put("orgId", loginInfo.getOrgId());
            employeeorgsvos = employeeMapper.selectEmployeesByParams(params);

        } else if (str.equals(String.valueOf(ManageDictCodeConstants.IAM_ORGANIZATION_SUB))) {
            params.put("orgIds", loginInfo.getOrgIds());
            employeeorgsvos = employeeMapper.selectEmployeesByParams(params);
        } else if (str.equals(String.valueOf(ManageDictCodeConstants.ORG_ALL))) {
            params.put("ownerCode", loginInfo.getOwnerCode());
            employeeorgsvos = employeeMapper.selectEmployeesByParams(params);
        } else {
            params.put("companyId", loginInfo.getCompanyId());
            employeeorgsvos = employeeMapper.selectEmployeesByParams(params);
        }
        return employeeorgsvos;
    }

    /**
     * 根据条件查询员工信息
     *
     * @author ：李贺
     * @date ：2019/9/19
     */
    @Override
    public IPage<EmployeeSearVO> employeeSearch(Page<EmployeeSearVO> page, SearchParamVO searchParamVO) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<EmployeeSearVO> result = employeeMapper.employeeSearch(page, searchParamVO, loginInfo.getCompanyId());
        page.setRecords(result);
        return page;
    }

    /**
     * 根据条件查询员工信息（提供索赔）
     *
     * @author ：谢志恺
     * @date ：2021/03/02
     */
    @Override
    public IPage<EmployeeSearClaimVO> employeeSearchClaim(Page<EmployeeSearClaimVO> page, SearchParamVO searchParamVO) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<EmployeeSearClaimVO> result = employeeMapper.employeeSearchClaim(page, searchParamVO, loginInfo.getCompanyId());
        page.setRecords(result);
        return page;
    }

    /**
     * 厂端查询经销商员工信息
     *
     * @author ：李贺
     * @date ：2019/12/13 @description：
     */
    @Override
    public IPage<EmployeeSearVO> factoryEmployeeSearch(Page<EmployeeSearVO> page, SearchParamVO searchParamVO) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<EmployeeSearVO> result = employeeMapper.factoryEmployeeSearch(page, searchParamVO, loginInfo.getAppId(),
                loginInfo.getCompanyId());
        page.setRecords(result);
        return page;
    }

    @Override
    public IPage<EmployeeSearBindVO> employeeSearchBind(Page<EmployeeSearBindVO> page,
                                                        SearchBindParamVO searchBindParamVO) {
        LoginInfoDto loginInfo = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        List<EmployeeSearBindVO> result = employeeMapper.employeeSearchBind(page, searchBindParamVO,
                loginInfo.getCompanyId());
        if (page.getCurrent() > page.getPages()) {
            Page<EmployeeSearBindVO> page2 = new Page(1, page.getSize());
            List<EmployeeSearBindVO> result2 = employeeMapper.employeeSearchBind2(page2, searchBindParamVO,
                    loginInfo.getCompanyId());
            page2.setRecords(result2);
            return page2;
        }
        page.setRecords(result);
        return page;
    }

    /**
     * 新增员工
     *
     * @author 李贺
     * @date 2019年09月19日
     */
    @Override
    @Transactional
    public Map<String, String> createEmployee(EmployeeAddVO employeeAddVO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        SmsWxVo smsWx = userLoginService.getSmsWx(loginInfoDto.getAppId());

        Integer type = employeeAddVO.getType();
        if (type == null) {
            type = 1;
        }
        if (type != 1 && type != 3) {
            throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, "type值不正确");
        }
        if (type == 3) {
            if (employeeAddVO.getEmpId() == null || employeeAddVO.getUserId() == null) {
                throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, "type为3时，empId,userId不能为空");
            }
        }
        Long companyId = loginInfoDto.getCompanyId();
        String appId = loginInfoDto.getAppId();
        /*
		 * LambdaQueryWrapper<EmployeePO> queryWrapper = new
		 * QueryWrapper<EmployeePO>().lambda();
		 * queryWrapper.eq(EmployeePO::getEmployeeNo, employeeAddVO.getEmployeeNo())
		 * .eq(EmployeePO::getAppId, appId) .eq(EmployeePO::getCompanyId, companyId);
		 * List<EmployeePO> empPoList = employeeMapper.selectList(queryWrapper); if
		 * (!CommonUtils.isNullOrEmpty(empPoList)) { if (employeeAddVO.getUserId() ==
		 * null || empPoList.size() > 1 || empPoList.get(0).getEmpId() !=
		 * employeeAddVO.getEmpId().longValue()) { throw new DMSAuthException(995,
		 * "该员工账号已存在"); } }
		 */


        UserPO userpos = userMapper.selectByAppUserCodeOr(appId, employeeAddVO.getUserCode());
        if (!ObjectUtils.isEmpty(userpos)) {
            throw new DMSAuthException(995, "该登录账号已被注册");
        }

        // 查看手机号是否已绑定在职人员
        Integer onJobCount = empMapper.selectOnJobCountByPhone(employeeAddVO.getMobilePhone(), loginInfoDto.getAppId(),
                employeeAddVO.getEmpId());
        if (onJobCount > 0) {
            throw new DMSAuthException(995, "该手机号已被注册");
        }

        Integer employeeStatus = employeeAddVO.getEmployeeStatus();
        // 保存emp表
        EmpPo empPo = BeanMapperUtil.copyProperties(employeeAddVO, EmpPo.class);
        empPo.setAppId(appId);
        empPo.setCompanyId(companyId.intValue());
        empPo.setValidStatus(ManageDictCodeConstants.STATUS_IS_YES);
        if (employeeStatus == ManageDictCodeConstants.EMPLOYEE_ISJOB) {
            empPo.setUserStatus(ManageDictCodeConstants.STATUS_QY);
        } else {
            empPo.setUserStatus(ManageDictCodeConstants.STATUS_JY);
        }
        empPo.setIsOnjob(employeeStatus);
        Integer gender = employeeAddVO.getGender();
        if (gender == null) {
            gender = ManageDictCodeConstants.GENDER_NOT_DEFINE;
        }
        empPo.setGender(gender);
        Long dataType = loginInfoDto.getDataType();
        Integer dataSource = null;
        if (dataType == ManageDictCodeConstants.DATA_TYPE_BY_OWNER) {
            dataSource = ManageDictCodeConstants.DATA_SOURCES_BY_OWNER;
        } else if (dataType == ManageDictCodeConstants.DATA_TYPE_BY_GROUP) {
            dataSource = ManageDictCodeConstants.DATA_SOURCES_BY_GROUP;
        } else if (dataType == ManageDictCodeConstants.DATA_TYPE_BY_SUPER) {
            dataSource = ManageDictCodeConstants.DATA_SOURCES_BY_SUPER;
        }
        empPo.setDataSources(dataSource);
        if (type == 1) {
            empMapper.insert(empPo);
        } else {
            empPo.setCreatedBy(loginInfoDto.getUserId().toString());
            empPo.setRecordVersion(1);
            empPo.setIsDeleted(0);
            empMapper.updateById(empPo);
        }
        // 保存user
        UserPO userpo = new UserPO();
        BeanMapperUtil.copyProperties(employeeAddVO, userpo);
        userpo.setAppId(appId);
        userpo.setEmpId(empPo.getEmpId().intValue());
        userpo.setCompanyId(companyId);
        StringBuilder password = new StringBuilder();
        if (smsWx.getSmsType() == ManageDictCodeConstants.STATUS_IS_YES) {
            // CMS-修改密码未固定 a12345678
            password.append("a12345678");
			/*
			 * char[] chars =
			 * "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM".toCharArray(); for
			 * (int i = 0; i < 7; i++) { if (i < 2) { int i1 = RandomUtils.nextInt(0,
			 * chars.length); password.append(chars[i1]); } else { Integer in =
			 * RandomUtils.nextInt(0, 10); password.append(in); } }
			 */
        } else {
            if (StringUtils.isNullOrEmpty(employeeAddVO.getPassword())) {
                throw new DMSAuthException(SysAuthCommonConstants.ERROR_CODE_996, "密码不能为空");
            }
            password = new StringBuilder(employeeAddVO.getPassword());
        }
        String newPassword = MD5Util.getEncryptedPwd(password.toString());
        userpo.setPassword(newPassword);
        userpo.setFailureNum(0);
        userpo.setIsDeleted(0);
        userpo.setLockCause(employeeAddVO.getLockCause());
        if (employeeStatus == ManageDictCodeConstants.EMPLOYEE_ISJOB) {
            userpo.setUserStatus(ManageDictCodeConstants.STATUS_QY);
        } else {
            userpo.setUserStatus(ManageDictCodeConstants.STATUS_JY);
        }
        if (type == 1) {
            userMapper.insert(userpo);
        } else {
            userpo.setCreatedBy(loginInfoDto.getUserId().toString());
            userpo.setIsDeleted(0);
            userpo.setRecordVersion(1);
            userMapper.updateById(userpo);
            QueryWrapper<EmployeePO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("EMP_ID", empPo.getEmpId()).eq("APP_ID", appId)
                    .eq("VALID_STATUS", ManageDictCodeConstants.STATUS_IS_YES)
                    .eq("EMPLOYEE_STATUS", ManageDictCodeConstants.EMPLOYEE_ISJOB);
            List<EmployeePO> employeepos = employeeMapper.selectList(queryWrapper);
            for (EmployeePO employeepo : employeepos) {
                employeepo.setValidStatus(ManageDictCodeConstants.STATUS_IS_NOT);
                employeepo.setEmployeeStatus(ManageDictCodeConstants.EMPLOYEE_NOJOB);
            }
        }

        EmployeePO employeepo = new EmployeePO();
        BeanMapperUtil.copyProperties(employeeAddVO, employeepo);
        // 保存employee
        if (type == 3) {
            LambdaQueryWrapper<EmployeePO> queryWrapper1 = new QueryWrapper<EmployeePO>().lambda();
            queryWrapper1.select(EmployeePO::getEmployeeId, EmployeePO::getEmployeeNo)
                    .eq(EmployeePO::getEmpId, empPo.getEmpId()).eq(EmployeePO::getCompanyId, companyId);
            List<EmployeePO> employeepos = employeeMapper.selectList(queryWrapper1);
            if (employeepos != null && employeepos.size() > 1) {
                employeeMapper.deleteByEmployeeIds(
                        employeepos.stream().map(EmployeePO::getEmployeeId).collect(Collectors.toList()));
            } else if (employeepos != null && employeepos.size() == 1) {
                employeepo.setEmployeeId(employeepos.get(0).getEmployeeId());
                employeepo.setEmployeeNo(employeepos.get(0).getEmployeeNo());
            }
        }
        employeepo.setAppId(appId);
        employeepo.setCompanyId(companyId);
        employeepo.setEmpId(empPo.getEmpId());
        employeepo.setDataType(loginInfoDto.getDataType().intValue());
        employeepo.setValidStatus(ManageDictCodeConstants.STATUS_IS_YES);
        employeepo.setEmployeeStatus(employeeStatus);
        employeepo.setOwnerCode(orgMapper.getOwerCodebyOrgId(employeepo.getOrgId()));
        if (employeepo.getEmployeeId() != null) {
            employeeMapper.updateById(employeepo);
        } else {
            Integer maxEmployeeNo = employeeMapper.findMaxEmployeeNo(employeepo.getCompanyId());
            int newNo = maxEmployeeNo + 1;
            String newEmployeeNo = Integer.toString(newNo);
            for (int i = newEmployeeNo.length(); i < 3; i++) {
                newEmployeeNo = "0" + newEmployeeNo;
            }
            newEmployeeNo = loginInfoDto.getCompanyCode() + newEmployeeNo;
            employeepo.setEmployeeNo(newEmployeeNo);
            employeeMapper.insert(employeepo);
        }

        sendpasswordSms(password.toString(), employeeAddVO.getMobilePhone());
        HashMap<String, String> map = new HashMap<>();
        map.put("employeeNo", employeepo.getEmployeeNo());
        map.put("employeeName", empPo.getEmployeeName());
        // 2019-12-17 【更改】将登陆密码显示-START
        map.put("password", password.toString());
        // 2019-12-17 【更改】将登陆密码显示-END
        return map;
    }

    /**
     * 短信登录密码发送
     *
     * @author ：李贺
     * @date ：Created in 2019/9/19
     * @modified By：
     */
    @Override
    public void sendpasswordSms(String password, String phone) {
		/*
		 * LoginInfoDto loginInfoDto =
		 * ApplicationContextHelper.getBeanByType(LoginInfoDto.class); SmsWxVo smsWx =
		 * userLoginService.getSmsWx(loginInfoDto.getAppId()); if (smsWx.getSmsType() !=
		 * ManageDictCodeConstants.STATUS_IS_NOT) { SmsPushDTO smsPushDTO = new
		 * SmsPushDTO(); smsPushDTO.setMobiles(phone);
		 * smsPushDTO.setTemplateId(smsTemplateId2); Map<String, String> params = new
		 * HashMap<>(); params.put("1", password); smsPushDTO.setParamMap(params); try {
		 * String f4Result = pushService.sendSms(smsPushDTO);
		 * logger.info("短信发送返回结果f4Result：{}", f4Result); } catch (Exception e) {
		 * logger.debug("短信发送失败", e); } }
		 */

    }

    /**
     * 编辑员工回显
     *
     * @author 李贺
     * @date 2019年09月20日
     */
    @Override
    public EmployeeAddVO findEmployeeByNo(String employeeNo, Long companyId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        if (companyId == null) {
            companyId = loginInfoDto.getCompanyId();
        }
        return employeeMapper.findEmployeeByNo(employeeNo, loginInfoDto.getAppId(), companyId);
    }

    /**
     * 编辑员工
     *
     * @author 李贺
     * @date 2019年09月20日
     */
    @Override
    @Transactional
    public Map<String, String> updateEmployee(EmployeeAddVO employeeInfoVO) {
        Map<String, String> map = new HashMap<>();
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String employeeNo = employeeInfoVO.getEmployeeNo();

        Integer employeeStatus = employeeInfoVO.getEmployeeStatus();
        Long companyId = loginInfoDto.getCompanyId();
        LambdaQueryWrapper<EmployeePO> query = new QueryWrapper<EmployeePO>().lambda();
        query.eq(EmployeePO::getEmployeeNo, employeeNo).eq(EmployeePO::getCompanyId, companyId);

        EmployeePO employeepo = employeeMapper.selectOne(query);

        Long empId = employeepo.getEmpId();
        EmpPo empPo = empMapper.selectById(empId);
        // zw 获取修改之前的姓名和手机
        String befempName = empPo.getEmployeeName();
        String befPhone = empPo.getMobilePhone();

        LambdaQueryWrapper<UserPO> lambdaQueryWrapper = new QueryWrapper<UserPO>().lambda();
        lambdaQueryWrapper.eq(UserPO::getEmpId, employeepo.getEmpId()).eq(UserPO::getAppId, employeepo.getAppId());
        UserPO userPo = userMapper.selectOne(lambdaQueryWrapper);
        // cms 1020/1/17 修改 检验手机号重复
        // 查看手机号是否已绑定在职人员
        // Integer onJobCount =
        // empMapper.selectOnJobCountByPhone(employeeInfoVO.getMobilePhone(),
        // loginInfoDto.getAppId(), employeeInfoVO.getEmpId());
        Integer onJobCount = empMapper.selectOnJobCountByPhone(employeeInfoVO.getMobilePhone(), loginInfoDto.getAppId(),
                null);
//        if (onJobCount > 0) {
//            map.put("type", "3");
//            map.put("data", "您输入的手机号码，与其他人员重复");
//            return map;
//        }
        if (onJobCount > 1) {
            map.put("type", "3");
            map.put("data", "您输入的手机号码，与其他人员重复");
            return map;
        }
        employeepo.setOrgId(employeeInfoVO.getOrgId());
        employeepo.setWorkgroupId(employeeInfoVO.getWorkgroupId());
        employeepo.setWorkerTypeId(employeeInfoVO.getWorkerTypeId());
        employeepo.setTechnicianGrade(employeeInfoVO.getTechnicianGrade());
        employeepo.setMaintainStationId(employeeInfoVO.getMaintainStationId());
        employeepo.setValidStatus(ManageDictCodeConstants.STATUS_IS_YES);
        employeepo.setEmployeeStatus(employeeStatus);
        employeepo.setDimissionDate(employeeInfoVO.getDimissionDate());
        employeepo.setFirstPost(employeeInfoVO.getFirstPost());
        employeepo.setSecondPost(employeeInfoVO.getSecondPost());
        employeepo.setThirdPost(employeeInfoVO.getThirdPost());
        employeepo.setDeputyStationId(employeeInfoVO.getDeputyStationId());
        employeepo.setOwnerCode(orgMapper.getOwerCodebyOrgId(employeepo.getOrgId()));
        employeeMapper.updateById(employeepo);

        empPo.setEmployeeName(employeeInfoVO.getEmployeeName());

        Integer gender = employeeInfoVO.getGender();
        if (gender == null) {
            gender = ManageDictCodeConstants.GENDER_NOT_DEFINE;
        }
        empPo.setGender(gender);
        empPo.seteMail(employeeInfoVO.geteMail());
        empPo.setMobilePhone(employeeInfoVO.getMobilePhone());
        empPo.setBirthday(employeeInfoVO.getBirthday());
        empPo.setIsOnjob(employeeStatus);
        empPo.setUserCode(employeeInfoVO.getUserCode());
        empPo.setValidStatus(ManageDictCodeConstants.STATUS_IS_YES);
        // empPo.setPhotos(employeeInfoVO.getPhotos());
        empPo.setNation(employeeInfoVO.getNation());
        empPo.setDrivingLevel(employeeInfoVO.getDrivingLevel());
        empPo.setDegreeEdu(employeeInfoVO.getDegreeEdu());
        empPo.setAge(employeeInfoVO.getAge());
        empPo.setAutoTime(employeeInfoVO.getAutoTime());
        empPo.setCooperationSchool(employeeInfoVO.getCooperationSchool());
        empPo.setGraduateSchool(employeeInfoVO.getGraduateSchool());
        empPo.setRemark(employeeInfoVO.getRemark());
        empMapper.updateById(empPo);

        LambdaQueryWrapper<UserPO> userpoquerywrapper = new QueryWrapper<UserPO>().lambda();
        userpoquerywrapper.eq(UserPO::getEmpId, empPo.getEmpId());
        UserPO userpo = userMapper.selectOne(userpoquerywrapper);
        Integer lockFlag = employeeInfoVO.getLockFlag();
        if (userpo.getLockFlag() == ManageDictCodeConstants.IS_IS_LOCK
                && lockFlag == ManageDictCodeConstants.NO_IS_LOCK) {
            userpo.setFailureNum(0);
            // 根据账号校验验证码
            String messageFormat = MessageFormat.format(SysAuthCommonConstants.VERIFICATION_CODE,
                    loginInfoDto.getAppId());
            redisClient.hdel(messageFormat, userpo.getUserCode());
            redisClient.hdel(messageFormat, "app");
            redisClient.hdel(messageFormat, "pc");
        }
        userpo.setLockFlag(lockFlag);
        userpo.setLockCause(employeeInfoVO.getLockCause());
        userpo.setIsDeleted(0);
        if (employeeStatus == ManageDictCodeConstants.EMPLOYEE_ISJOB) {
            userpo.setUserStatus(ManageDictCodeConstants.STATUS_QY);
        } else {
            userpo.setUserStatus(ManageDictCodeConstants.STATUS_JY);
        }


        userMapper.updateById(userpo);
        LambdaQueryWrapper<UserOrgPO> poLambdaQueryWrapper = new QueryWrapper<UserOrgPO>().lambda();
        poLambdaQueryWrapper.eq(UserOrgPO::getUserId, userpo.getUserId());
        List<UserOrgPO> userorgpos = userOrgMapper.selectList(poLambdaQueryWrapper);
        for (UserOrgPO userorgpo : userorgpos) {
            userorgpo.setOrgId(employeeInfoVO.getOrgId());
            userOrgMapper.updateById(userorgpo);
        }


        try {
            redisClient.hdel("cyxdms:sysAuth:user:10041001", userpo.getUserId().toString());
            redisClient.hdel("cyxdms:sysAuth:user:10041002", userpo.getUserId().toString());
            redisClient.hdel(BaseDataCommonConstants.USER_CACHE_USERID, userpo.getUserId().toString());
        } catch (Exception e) {
            logger.error("redis服务挂了");
        }
//        if (employeeStatus == ManageDictCodeConstants.EMPLOYEE_NOJOB) {
//            // 员工离职更新自动分配顾问状态
//            customerService.updateConsultantWork(userPo.getUserId());
//        }

        map.put("type", "1");
        // 判断是否修改了姓名或者手机号 如有任一修改则调用汽车之家厂商顾问修改接口
//        if (!befempName.equals(employeeInfoVO.getEmployeeName()) || !befPhone.equals(employeeInfoVO.getMobilePhone())) {
//            Map<String, Object> param = new HashMap<>();
//            param.put("userId", userPo.getUserId());
//            param.put("employeeName", employeeInfoVO.getEmployeeName());
//            param.put("mobilePhone", employeeInfoVO.getMobilePhone());
//            param.put("dealerCode", loginInfoDto.getOwnerCode());
//            datacenterService.producerUpdateAdviser(param);
//        }
        return map;
    }

    /**
     * 修改权限 职位列表
     *
     * @author 李贺
     * @date 2019年09月20日
     */
    @Override
    public IPage<PositionVO> findPosition(Page page, String employeeNo) {

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return employeeMapper.findPosition(page, employeeNo, loginInfoDto.getAppId());

    }

    /**
     * 添加用户角色
     *
     * @author 李贺
     * @date 2019年09月20日
     */
    @Override
    @Transactional
    public PositionVO addRole(AddRolePO addrolepo) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long dataType = loginInfoDto.getDataType();
        String appId = loginInfoDto.getAppId();
        String employeeNo = addrolepo.getEmployeeNo();
        Long orgId = addrolepo.getOrgId();
        Integer userId = employeeMapper.findUserIdByNo(employeeNo, appId, loginInfoDto.getCompanyId());


        List<Long> roleIds = addrolepo.getRoleId();

        if (roleIds.size() == 0) {
            throw new ServiceBizException("请选择角色");
        }

        boolean isRole = false;
        for (Long l : roleIds) {
            RolePO role = roleMapper.selectById(l);
            if (BaseDataCommonConstants.ISJL.equals(role.getRoleCode())//IS经理
                    || BaseDataCommonConstants.CWBJRKRY.equals(role.getRoleCode())
                    || BaseDataCommonConstants.XSGLBJRGLY.equals(role.getRoleCode())) {
                isRole = true;
                UserPO user = userMapper.selectById(userId);
                user.setRegId(role.getRoleCode());
                user.setUpdatedAt(LocalDateTime.now());
                userMapper.updateById(user);
            }
        }


        Long userOrgId = addrolepo.getUserOrgId();

        if (userOrgId != null) {
            UserOrgPO userorgpo = userOrgMapper.selectById(userOrgId);
            userorgpo.setOrgId(orgId);
            String owerCode = orgMapper.getOwerCodebyOrgId(userorgpo.getOrgId());
            Long ownerId = orgMapper.getOwnerIdByOrgId(userorgpo.getOrgId());
            if (!StringUtils.isNullOrEmpty(ownerId)) {
                OrgPO orgpo = orgMapper.selectById(ownerId);
                userorgpo.setOwnerOrgType(orgpo.getOrgType());
            }
            userorgpo.setOwnerCode(owerCode);
            userOrgMapper.updateById(userorgpo);
            // 逻辑删除 原有角色的权限
            permissionMenuMapper.updateOldRolePer(userOrgId);

            permissionMenuMapper.updateNewRolePer(userOrgId, roleIds);

            permissionMenuMapper.insertOtherMenu(userOrgId, loginInfoDto.getAppId(), loginInfoDto.getUserId(),
                    dataType);

            orgRoleMapper.deleteByUserOrgId(userOrgId);
            for (Long roleId : roleIds) {
                OrgRolePO orgrolepo = new OrgRolePO();
                orgrolepo.setUserOrgId(userOrgId);
                orgrolepo.setRoleId(roleId);
                orgrolepo.setIsDeleted(0);
                orgRoleMapper.insert(orgrolepo);
            }

            permissionMenuActionMapper.deleteUserAction(userOrgId);
            permissionMenuRangeMapper.deleteUserRange(userOrgId);
            permissionCtrlMapper.deletePermissionCtrlByUserOrgId(userOrgId);
            permissionCtrlMapper.addUserPermissionCtrl(userOrgId, roleIds, userId, appId);

            permissionMenuRangeMapper.insertRangeByOthers(roleIds, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE,
                    userOrgId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, loginInfoDto.getUserId().toString());
            permissionMenuActionMapper.insertActionByOthers(roleIds, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE,
                    userOrgId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, loginInfoDto.getUserId().toString());

        } else {
            // 插入 userOrg
            UserOrgPO userorgpo1 = new UserOrgPO();
            userorgpo1.setUserId(userId.longValue());
            userorgpo1.setOrgId(orgId);
            userorgpo1.setRecordVersion(0);
            userorgpo1.setIsDeleted(0);
            String ownerCode = userOrgMapper.findOwnerCode(orgId.intValue());
            Long ownerId = orgMapper.getOwnerIdByOrgId(orgId);
            if (!StringUtils.isNullOrEmpty(ownerId)) {
                OrgPO orgpo = orgMapper.selectById(ownerId);
                userorgpo1.setOwnerOrgType(orgpo.getOrgType());
            }
            userorgpo1.setOwnerCode(ownerCode);
            userOrgMapper.insert(userorgpo1);

            userOrgId = userorgpo1.getUserOrgId();

            // 删除脏数据
            List<Long> permissionMenuIds = permissionMenuMapper.queryIdByUserOrgId(userOrgId);
            if (permissionMenuIds.size() != 0) {
                // 删除所有 该组织下所有用户权限
                permissionMenuActionMapper.deletePMA(permissionMenuIds);
                permissionMenuRangeMapper.deletePMR(permissionMenuIds);
                permissionMenuMapper.deletePM(permissionMenuIds);
            }
            permissionCtrlMapper.deletePermissionCtrlByUserOrgId(userOrgId);

            for (Long newRoleId : roleIds) {
                // 插入orgRole
                OrgRolePO orgrolepo = new OrgRolePO();
                orgrolepo.setUserOrgId(userOrgId);
                orgrolepo.setRoleId(newRoleId);
                orgrolepo.setIsDeleted(0);
                orgRoleMapper.insert(orgrolepo);
            }
            Long createdBy = loginInfoDto.getUserId();
            permissionMenuMapper.insertUserMenu(roleIds, userOrgId, createdBy, appId);
            permissionMenuMapper.insertOtherMenu(userOrgId, loginInfoDto.getAppId(), createdBy, dataType);
            permissionCtrlMapper.addUserPermissionCtrl(userOrgId, roleIds, userId, appId);
            permissionMenuRangeMapper.insertRangeByOthers(roleIds, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE,
                    userOrgId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, loginInfoDto.getUserId().toString());
            permissionMenuActionMapper.insertActionByOthers(roleIds, ManageDictCodeConstants.BILL_TYPE_PERMISSION_ROLE,
                    userOrgId, ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, loginInfoDto.getUserId().toString());

			/*
			 * List<UserPermissionMenuVO> perMenus =
			 * permissionMenuMapper.selectPermissionMenuIds(roleIds);
			 *
			 * if (perMenus.size() != 0) { for (UserPermissionMenuVO perMenu : perMenus) {
			 * Long menuId = perMenu.getMenuId(); Long permissionMenuId =
			 * permissionMenuMapper.findPermissionMenuId(menuId, userOrgId); if
			 * (permissionMenuId != null) { PermissionMenuActionPO permissionMenuActionPO =
			 * new PermissionMenuActionPO();
			 * permissionMenuActionPO.setMenuCuringId(perMenu.getMenuCuringId().intValue());
			 * permissionMenuActionPO.setIsDeleted(0);
			 * permissionMenuActionPO.setPermissionMenuId(permissionMenuId.intValue());
			 * permissionMenuActionPO.setIsEmpowered(perMenu.getIsEmpowered());
			 * permissionMenuActionPO.setIsFlexible(perMenu.getIsFlexible());
			 * permissionMenuActionMapper.insert(permissionMenuActionPO); } } }
			 *
			 * List<UserPermissionRangeVO> perMenus2 =
			 * permissionMenuRangeMapper.selectPermissionMenuIds(roleIds); if
			 * (perMenus2.size() != 0) { for (UserPermissionRangeVO userPermissionRangeVO :
			 * perMenus2) {
			 *
			 * Long menuId = userPermissionRangeVO.getMenuId(); Long permissionMenuId =
			 * permissionMenuMapper.findPermissionMenuId(menuId, userOrgId); if
			 * (permissionMenuId != null) { PermissionMenuRangePO permissionMenuRangePO =
			 * new PermissionMenuRangePO();
			 * permissionMenuRangePO.setMenuRangeId(userPermissionRangeVO.getMenuRangeId().
			 * intValue()); permissionMenuRangePO.setIsDeleted(0);
			 * permissionMenuRangePO.setPermissionMenuId(permissionMenuId.intValue());
			 * permissionMenuRangePO.setIsEmpowered(userPermissionRangeVO.getIsEmpowered());
			 * permissionMenuRangePO.setIsFlexible(userPermissionRangeVO.getIsFlexible());
			 * permissionMenuRangeMapper.insert(permissionMenuRangePO); } } }
			 */
        }
        // CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-START
        supplementRegionalManager(Long.valueOf(userId));
        // CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-END

        // 判断该顾问是否含有顾问角色
        Integer count = userOrgMapper.getIsConsultant(userId);
        if (count > 0) {
            // 包含销售顾问或者网销顾问角色需要调用汽车之家接口
            Map<String, Object> param = userOrgMapper.getUserInfo(userId);
            System.out.println(loginInfoDto.getOwnerId());
            param.put("dealerCode", loginInfoDto.getOwnerCode());
            datacenterService.producerAddAdviser(param);
        } else {
            System.out.println("不包含顾问角色不需要传递");
        }

        return employeeMapper.findUserOrgPosition(userOrgId);

    }

    /**
     * 获得用户可选角色列表
     *
     * @author 李贺
     * @date 2019年09月21日
     */

    @Override
    public List<FindRoleVO> findRole(String employeeNo, Long orgId, Integer isAdd) {
        Integer roleType = 0 ;
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);

        Long companyId = loginInfoDto.getCompanyId();
        Integer companyType = companyMapper.queryComTypeById(companyId);
        Integer factoryId = companyMapper.queryFactoryIdByAppId(loginInfoDto.getAppId());
        OrgPO orgPO = orgMapper.selectById(orgId);
        if (!ObjectUtils.isEmpty(orgPO)){
            Integer orgType = orgPO.getOrgType();
            if (orgType == ManageDictCodeConstants.ORG_TYPE_SALE || orgType == ManageDictCodeConstants.ORG_TYPE_SALE_WAR || orgType == ManageDictCodeConstants.ORG_TYPE_SALE_BIG || orgType == ManageDictCodeConstants.ORG_TYPE_SALE_SMALL){
                Integer roleTypeOne = ManageDictCodeConstants.ROLE_TYPE_SALE;
                return roleMapper.findAllRole(companyId, companyType, factoryId, loginInfoDto.getAppId(),roleTypeOne);
            }else if (orgType == ManageDictCodeConstants.ORG_TYPE_SERVICE || orgType == ManageDictCodeConstants.ORG_TYPE_SERVICE_WAR || orgType == ManageDictCodeConstants.ORG_TYPE_SERVICE_BIG || orgType == ManageDictCodeConstants.ORG_TYPE_SERVICE_SMALL){
                Integer roleTypeTwo = ManageDictCodeConstants.ROLE_TYPE_SERVICE;
                return roleMapper.findAllRole(companyId, companyType, factoryId, loginInfoDto.getAppId(),roleTypeTwo);
            }else if (orgType == ManageDictCodeConstants.ORG_TYPE_SALEAREA ){
                Integer roleTypeThree = ManageDictCodeConstants.ROLE_TYPE_PART;
                return roleMapper.findAllRole(companyId, companyType, factoryId, loginInfoDto.getAppId(),roleTypeThree);
            }
        }
        return roleMapper.findAllRole(companyId, companyType, factoryId, loginInfoDto.getAppId(),roleType);
    }

    @Override
    public Map<String, List<FindRolePositionVO>> findRole2(Long userOrgId) {

        Map<String, List<FindRolePositionVO>> map = new HashMap<>();
        List<CodeDTO> tcCodes = findTcCodeByType(1006L);
        List<Integer> list = new ArrayList<>();
        for (CodeDTO tcCode : tcCodes) {
            Integer codeId = tcCode.getCodeId();
            list.add(codeId);
        }
        List<FindRolePositionVO> findrolevo1 = roleMapper.findRoleByCodes(userOrgId, list);
        Iterator<FindRolePositionVO> iter1 = findrolevo1.iterator();
        while (iter1.hasNext()) {
            FindRolePositionVO next = iter1.next();
            if (next.getIsHave() == 0) {
                iter1.remove();
            }
        }
        map.put("before", findrolevo1);

        List<CodeDTO> tcCodes2 = findTcCodeByType(1007L);
        List<Integer> list2 = new ArrayList<>();
        for (CodeDTO tcCode : tcCodes2) {
            Integer codeId = tcCode.getCodeId();
            list2.add(codeId);
        }
        List<FindRolePositionVO> findrolevo2 = roleMapper.findRoleByCodes(userOrgId, list2);
        Iterator<FindRolePositionVO> iter2 = findrolevo2.iterator();
        while (iter2.hasNext()) {
            FindRolePositionVO next = iter2.next();
            if (next.getIsHave() == 0) {
                iter2.remove();
            }
        }
        map.put("after", findrolevo2);
        return map;
//
    }

    /**
     * 更新用户权限
     *
     * @author 李贺
     * @date 2019年09月21日
     */
    @Override
    @Transactional
    public void updatePermission(UserPermissionPO userpermissionpo) {

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appId = loginInfoDto.getAppId();
        Integer type = ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER;

        Long userOrgId = userpermissionpo.getUserOrgId();

        UserOrgPO userorgpo = userOrgMapper.selectById(userOrgId);
        Long userId = userorgpo.getUserId();

        List<Long> oldMenuIds = userpermissionpo.getOldMenuId();
        List<Long> menuIds = userpermissionpo.getMenuId();

        List<Long> deleteMenuIds = new ArrayList<>();
        for (Long oldMenu : oldMenuIds) {
            if (!menuIds.contains(oldMenu)) {
                deleteMenuIds.add(oldMenu);
            }
        }
        // 删除 permissionMeun
        permissionMenuMapper.deletePermissionMenus(type, userOrgId, deleteMenuIds);

        // 新增菜单
        for (Long menuId : menuIds) {
            if (!oldMenuIds.contains(menuId)) {
                PermissionMenuPO permissionmenupo = new PermissionMenuPO();
                permissionmenupo.setAppId(appId);
                permissionmenupo.setPermissionType(type);
                permissionmenupo.setPermissionId(userOrgId.intValue());
                permissionmenupo.setIsFlexible(ManageDictCodeConstants.STATUS_IS_YES);
                permissionmenupo.setIsEmpowered(ManageDictCodeConstants.STATUS_IS_YES);
                permissionmenupo.setMenuId(menuId);
                permissionMenuMapper.insert(permissionmenupo);
            }
        }

        // 删除按钮
        List<Long> menuActionId = userpermissionpo.getMenuActionId();
        List<Long> oldMenuActionId = userpermissionpo.getOldMenuActionId();

        List<Long> deleteMenuActionIds = new ArrayList<>();
        for (Long oldMenuAction : oldMenuActionId) {
            if (!menuIds.contains(oldMenuAction)) {
                deleteMenuActionIds.add(oldMenuAction);
            }
        }
//        jwtService.delJwtInfo(userId.toString());

//        permissionMenuActionMapper.deletePermissionMenuAction(type, userOrgId, deleteMenuActionIds);

    }

    /**
     * 根据用户的userOrgId查询用户的角色Id
     *
     * @return
     * @author 李贺
     * @date 2019年09月23日
     */
    @Override
    public List<Long> findRoleIds(Long userOrgId) {

        return employeeMapper.findRoleIds(userOrgId);
    }

    @Override
    public Map<String, String> findClueSourceids(Long userOrgId) {
        LambdaQueryWrapper<UserorgSourcePO> query = new QueryWrapper<UserorgSourcePO>().lambda();
        query.eq(UserorgSourcePO::getUserOrgId, userOrgId);
        UserorgSourcePO po = userorgSourceService.getOne(query);
        if (null != po) {
            Map<String, String> rlt = new HashMap<String, String>();
            rlt.put("clueSourceIds", po.getClueSourceids());
            rlt.put("clueSourceNames", po.getClueSourceNames());
            return rlt;
        }
        return null;
    }

    /**
     * 保存用户权限
     *
     * @return
     * @author 李贺
     * @date 2019年09月24日
     */
    @Override
    @Transactional
    public void savePermission(RolePDto rolepdto) {

        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        String appId = loginInfoDto.getAppId();
        Long userId = loginInfoDto.getUserId();

        Long userOrgId = rolepdto.getUserOrgId();
        // 添加责任线索来源
        if (10461003 == loginInfoDto.getDataType() && null != rolepdto.getClueSourceIds()) {
            LambdaQueryWrapper<UserorgSourcePO> query = new QueryWrapper<UserorgSourcePO>().lambda();
            query.eq(UserorgSourcePO::getUserOrgId, userOrgId);
            UserorgSourcePO po = userorgSourceService.getOne(query);
            if (null != po) {
                po.setClueSourceids(rolepdto.getClueSourceIds());
                po.setClueSourceNames(rolepdto.getClueSourceNames());
                userorgSourceService.updateById(po);
            } else {
                UserorgSourceDTO userorgSourceDTO = new UserorgSourceDTO();
                userorgSourceDTO.setUserOrgId(userOrgId.toString());
                userorgSourceDTO.setClueSourceids(rolepdto.getClueSourceIds());
                userorgSourceDTO.setClueSourceNames(rolepdto.getClueSourceNames());
                userorgSourceService.insert(userorgSourceDTO);
            }
        }

        String nowTree = rolepdto.getNowTree();
        String treeMenuAction = rolepdto.getTreeMenuAction();
        String treeMenuRange = rolepdto.getTreeMenuRange();/////
        List<String> maintain = rolepdto.getMaintain();
        List<String> accessories = rolepdto.getAccessories();
        List<String> vehicleWarehouse = rolepdto.getVehicleWarehouse();// 整车仓库
        List<String> accessoriesWarehouse = rolepdto.getAccessoriesWarehouse();// 配件仓库
        List<String> suppliesWarehouse = rolepdto.getSuppliesWarehouse();// 用品仓库
        List<String> checkedListSettlement = rolepdto.getCheckedListSettlement(); // 结算1314
        List<String> favorableModels = rolepdto.getFavorableModels();// 优惠模式
        List<String> checkedListMaintenanceType = rolepdto.getCheckedListMaintenanceType();// 维修类型

        List<String> claimWarehouse = rolepdto.getClaimWarehouse();// 索赔回运仓库

        String userorgId = userOrgId.toString();
        if (StringUtils.isNullOrEmpty(nowTree)) {// 菜单权限不能为空
            throw new ServiceBizException("菜单权限不能为空");
        }
        permissionMenuMapper.insertOtherMenus(userOrgId, appId, loginInfoDto.getUserId(), loginInfoDto.getDataType());

        permissionMenuMapper.updateOldRolePer(userOrgId);

        String[] sourceStrArray = nowTree.split(",");
        if (sourceStrArray.length != 0) {
            permissionMenuMapper.updateByMenuIds(userOrgId, sourceStrArray, loginInfoDto.getUserId());
        }

        //查询该职位对应角色的权限，并将用户权限中响应的权限version置为1
        List<OrgRolePO> orgRolePoList = orgRoleMapper.selectList(new LambdaQueryWrapper<OrgRolePO>().eq(OrgRolePO::getUserOrgId, userorgId));
        List<Long> roleIds = orgRolePoList.stream().map(t -> t.getRoleId()).collect(Collectors.toList());
        List<PermissionMenuPO> rolePermissionList = permissionMenuMapper.selectList(new LambdaQueryWrapper<PermissionMenuPO>().select(PermissionMenuPO::getMenuId)
                .eq(PermissionMenuPO::getPermissionType, ManageDictCodeConstants.PERMISSION_TYPE_ROLE)
                .in(PermissionMenuPO::getPermissionId, roleIds)
                .eq(PermissionMenuPO::getIsEmpowered, ManageDictCodeConstants.STATUS_IS_YES));
        List<Long> menuList = rolePermissionList.stream().map(t -> t.getMenuId()).collect(Collectors.toList());

        if(CollectionUtils.isNotEmpty(menuList)){
            permissionMenuMapper.updateRecordVersion(userorgId, menuList);
        }

        permissionCtrlMapper.deletePermissionCtrlByUserOrgId(userOrgId);
        // 删除menuCtrl内容
        if (!CommonUtils.isNullOrEmpty(maintain)) {
            Integer type = ManageDictCodeConstants.MAINTAIN;
            permissionCtrlMapper.insertCtrl(maintain, type, userOrgId, appId, userId);
        }
        if (!CommonUtils.isNullOrEmpty(accessories)) {
            Integer type = ManageDictCodeConstants.ACCESSORIES;
            permissionCtrlMapper.insertCtrl(accessories, type, userOrgId, appId, userId);
        }
        if (!CommonUtils.isNullOrEmpty(vehicleWarehouse)) {
            Integer type = ManageDictCodeConstants.VEHICLE_WAREHOUSE;
            permissionCtrlMapper.insertCtrl(vehicleWarehouse, type, userOrgId, appId, userId);
        }
        if (!CommonUtils.isNullOrEmpty(accessoriesWarehouse)) {
            Integer type = ManageDictCodeConstants.ACCESSORIES_WAREHOUSE;
            permissionCtrlMapper.insertCtrl(accessoriesWarehouse, type, userOrgId, appId, userId);
        }
        if (!CommonUtils.isNullOrEmpty(claimWarehouse)) {
            Integer type = ManageDictCodeConstants.CLAIM_WAREHOUSE;
            permissionCtrlMapper.insertCtrl(claimWarehouse, type, userOrgId, appId, userId);
        }
        if (!CommonUtils.isNullOrEmpty(favorableModels)) {
            Integer type = ManageDictCodeConstants.FAVORABLE_MODELS;
            permissionCtrlMapper.insertCtrl(favorableModels, type, userOrgId, appId, userId);
        }
        if (!CommonUtils.isNullOrEmpty(checkedListSettlement)) {
            Integer type = ManageDictCodeConstants.SETTLEMENT;
            permissionCtrlMapper.insertCtrl(checkedListSettlement, type, userOrgId, appId, userId);
        }
        if (!CommonUtils.isNullOrEmpty(suppliesWarehouse)) {
            Integer type = ManageDictCodeConstants.SUPPLIES_WAREHOUSE;
            permissionCtrlMapper.insertCtrl(suppliesWarehouse, type, userOrgId, appId, userId);
        }
        if (!CommonUtils.isNullOrEmpty(checkedListMaintenanceType)) {
            Integer type = ManageDictCodeConstants.CHECKED_LIST_MAINTENANCE_TYPE;
            permissionCtrlMapper.insertCtrl(checkedListMaintenanceType, type, userOrgId, appId, userId);
        }
        // treeMenuAction

        permissionMenuActionMapper.deleteUserAction(userOrgId);
        permissionMenuRangeMapper.deleteUserRange(userOrgId);

        if (!StringUtils.isNullOrEmpty(treeMenuAction)) {
            String[] oneAction = treeMenuAction.split(";");
            if (oneAction.length > 0) {
                for (int i = 0; i < oneAction.length; i++) {
                    if (!StringUtils.isNullOrEmpty(oneAction[i])) {
                        roleMenuActionService.editOneAction(oneAction[i],
                                ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userorgId);
                    }
                }
            }
        }
        // treeMenuRange
        if (!StringUtils.isNullOrEmpty(treeMenuRange)) {
            String[] oneRange = treeMenuRange.split(";");
            if (oneRange.length > 0) {
                for (int i = 0; i < oneRange.length; i++) {
                    if (!StringUtils.isNullOrEmpty(oneRange[i])) {
                        roleMenuRangeService.editOneRange(oneRange[i],
                                ManageDictCodeConstants.BILL_TYPE_PERMISSION_USER, userorgId);

                    }
                }
            }
        }

        UserOrgPO userorgpo = userOrgMapper.selectById(userOrgId);
        Long userId1 = userorgpo.getUserId();

//        jwtService.delJwtInfo(userId1.toString());
        // CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-START
        supplementRegionalManager(userId);
        // CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-END
    }

    /**
     * 删除员工职位
     *
     * @return
     * @author 李贺
     * @date 2019年09月24日
     */
    @Override
    @Transactional
    public void deleteUserOrg(Long userOrgId) {
        List<Long> permissionMenuIds = permissionMenuMapper.queryIdByUserOrgId(userOrgId);

        if (permissionMenuIds.size() != 0) {
            // 删除所有 该组织下所有用户权限
            permissionMenuActionMapper.deletePMA(permissionMenuIds);
            permissionMenuRangeMapper.deletePMR(permissionMenuIds);
            permissionMenuMapper.deletePM(permissionMenuIds);
        }
        permissionCtrlMapper.deletePermissionCtrlByUserOrgId(userOrgId);

        LambdaQueryWrapper<OrgRolePO> queryWrapper = new QueryWrapper<OrgRolePO>().lambda();
        queryWrapper.eq(OrgRolePO::getUserOrgId, userOrgId);

        orgRoleMapper.deleteByUserOrgId(userOrgId);

        UserOrgPO userorgpo = userOrgMapper.selectById(userOrgId);

        userOrgMapper.deleteByUserOrgId(userOrgId);

        Long userId1 = userorgpo.getUserId();
//        jwtService.delJwtInfo(userId1.toString());
        // CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-START
        supplementRegionalManager(userId1);
        // CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-END
    }

    @Override
    @Transactional
    public List<Map<String, Object>> getEmployee(String time) {
        return employeeMapper.getEmployee(time);
    }

    /**
     * 绑定/变更手机号
     *
     * @return
     * @author 李贺
     * @date 2019年11月5日
     */
    @Override
    @Transactional
    public void updatePhone(BindingPhoneVO bindingPhoneVO) {
        String phone = bindingPhoneVO.getPhone();
        Integer type = bindingPhoneVO.getType();
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long empId = loginInfoDto.getEmpId();
        EmpPo empPo = empMapper.selectById(empId);
        String appId = loginInfoDto.getAppId();
        if (type == 1) {
            String checkCode = bindingPhoneVO.getCheckCode();
            userLoginService.comCheckCode((short) 1, phone, checkCode);
            Integer count = empMapper.findCountByPhoneAndAppIdAndEmpId(phone, appId, empId);
            if (count > 0) {
                throw new DMSAuthException(SysAuthCommonConstants.ERROR_CODE_996, "当前手机号绑定过多");
            }
        } else {
            empMapper.updatePhoneByPhone(phone, appId);
        }
        empPo.setMobilePhone(phone);
        empMapper.updateById(empPo);
    }

    /**
     * 获得是否绑定微信信息
     *
     * @return
     * @author 李贺
     * @date 2019年11月5日
     */
    @Override
    public Map<String, String> getWeChatBinding() {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long empId = loginInfoDto.getEmpId();
        EmpPo empPo = empMapper.selectById(empId);
        String openId = empPo.getOpenId();
        Map<String, String> map = new HashMap<>();
        if (!StringUtils.isNullOrEmpty(openId)) {
            String wechat = empMapper.findWechatByOpenIdAndAppId(openId, loginInfoDto.getAppId());
            map.put("type", "2");
            map.put("data", wechat != null ? wechat : "");
        } else {
            map.put("type", "1");
            map.put("data", wechatScanLoginService.wechatLoginUrl(redirectUri).get("url"));
        }
        return map;
    }

    /**
     * 绑定/解绑微信
     *
     * @return
     * @author 李贺
     * @date 2019年11月5日
     */
    @Override
    @Transactional
    public Map<String, String> updateWeChatBinding(WechatInfo wechatInfo) {
        Integer type = wechatInfo.getType();
        if (type != 1 && type != 2 && type != 3) {
            throw new DMSAuthException(SysAuthCommonConstants.OT_CODE, "type值不正确");
        }
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        Long empId = loginInfoDto.getEmpId();
        EmpPo empPo = empMapper.selectById(empId);
        String openId = wechatInfo.getOpenid();
        Map<String, String> map = new HashMap<>();
        if (type.equals(1)) {
            if (!StringUtils.isNullOrEmpty(openId)) {
                String employeeNo = empMapper.findEmployeeNoByOpenIdAndAppId(openId, loginInfoDto.getAppId());
                if (!StringUtils.isNullOrEmpty(employeeNo)) {
                    map.put("type", "2");
                    map.put("data", employeeNo);
                    return map;
                }
            }
            empPo.setOpenId(wechatInfo.getOpenid());
            empPo.setHeadPortrait(wechatInfo.getHeadimgurl());
            empPo.setWechat(wechatInfo.getNickname());
        } else if (type.equals(2)) {
            empMapper.updateOpenId(openId, loginInfoDto.getAppId());
            empPo.setOpenId(wechatInfo.getOpenid());
            empPo.setHeadPortrait(wechatInfo.getHeadimgurl());
            empPo.setWechat(wechatInfo.getNickname());
        } else if (type.equals(3)) {
            empPo.setOpenId(null);
            empPo.setHeadPortrait(null);
            empPo.setWechat(null);
        }
        empMapper.updateById(empPo);
        map.put("type", "1");
        map.put("data", "成功");
        return map;
    }

    // CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-START

    /**
     * 根据 USER_ID，ORG_TYPE，POSITION_CODE（或更多） 查询
     *
     * @return
     * @author baiyuxin
     * @date 2019年11月5日
     */
    @Override
    public List<Map<String, Object>> findUserOrgRolePosition(Map<String, Object> queryParam) {
        return employeeMapper.findUserOrgRolePosition(queryParam);
    }

    public boolean isUserOrgRolePosition(Long userId) {
        Map<String, Object> queryParams = com.google.common.collect.Maps.newHashMap();
//		queryParams.put("orgType","15061005");
        queryParams.put("userId", userId);
        // todo 改成常量
        queryParams.put("positionCodes", "10991001");
        List<Map<String, Object>> queryList = findUserOrgRolePosition(queryParams);
        return queryList != null && !queryList.isEmpty();
    }

    public void supplementRegionalManager(Long userId) {
        com.yonyou.cms.channel.client.service.message.CmsChannelCommonService cmsChannelCommonService = ApplicationContextHelper
                .getBeanByType(com.yonyou.cms.channel.client.service.message.CmsChannelCommonService.class);
        Map<String, Object> params = com.google.common.collect.Maps.newHashMap();
        params.put("userId", userId);
        if (isUserOrgRolePosition(userId)) {
            // 处理数据返给接口（事业部，办事处，用户ID）
            cmsChannelCommonService.supplementRegionalManager(params);
        } else {
            // 删除旧数据（delflag）
            cmsChannelCommonService.deleteRegionalManager(params);
        }
    }

    // CMS-更改-{1850【经销商区域经理维护】人员角色属性包含“区域经理”的，人员角色分配后自动带入到区域经理维护功能中}-END

    /**
     * 店铺默认接听电话配置接口
     *
     * @author zw
     * @date 2020年09月29日
     */
    @Override
    @SuppressWarnings("rawtypes")
    public RestResultResponse delaultPhoneSet(String dealerCode) {
        Map<String, Object> params = userOrgMapper.delaultPhoneSet(dealerCode);
        RestResultResponse response = new RestResultResponse();
        if (null != params) {
            response = datacenterService.delaultPhoneSet(params);
        } else {
            response.setResultCode(500);
            response.setErrMsg(dealerCode + "没有带中文的顾问");
            response.setSuccess(false);
        }
        return response;
    }

    @Override
    public List<EmployeeVO> getEmployeeByUserIds(String userIds) {
        String[] userIdArray = null;
        if (!StringUtils.isBlank(userIds)) {
            userIdArray = userIds.split(",");
            List<EmployeeVO> result = employeeMapper.getEmployeeByUserIds(userIdArray);
            return result;
        }
        return null;
    }
}
